﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Kaio.Core;
using Kaio.Web.UI;
using Kaio.Web.UI.Attributes;
using MvcForum.Net.Bussiness;
using MvcForum.Net.FileManager;

namespace MvcForum.Net.Controllers
{

    [ValidateAuthentication]
    [IsNotModified(Order = 2)]
    [RemoveHtmlWhiteSpace(Order = 3)]
    public class CpanelController : Controller
    {
        //
        // GET: /Cpanel/


        private List<ForumUrl> Address
        {
            get
            {
                return new List<ForumUrl>
                          {
                              new ForumUrl
                                  {
                                      Title = ForumContext.GetText(LanguageSection.CPANEL, "PAGE_NAME"),
                                      Url = ForumContext.GetAbsoluteUrl(ForumUrls.CONTROL_PANEL)
                                  }
                          };
            }
        }


        public ActionResult Index()
        {

            ViewBag.ActiveUrl = Address[0];

            ViewBag.NavAddress = Address;

            var _u = UsersRepo.Info(ForumContext.UserInfo.UserId);

            return View(_u);
        }


        #region Change Email Pwd

        public ActionResult ChangeEmailPwd()
        {

            var url = new ForumUrl
                                    {
                                        Title = ForumContext.GetText(LanguageSection.CHANGE_EMAIL_PASSWORD, "PAGE_NAME"),
                                        Url = ForumContext.GetAbsoluteUrl(ForumUrls.CHANGE_EMAIL_PASSWORD)
                                    };


            ViewBag.ActiveUrl = url;
            var _address = Address;
            _address.Add(url);
            ViewBag.NavAddress = _address;

            return View();

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult ChangeEmailPwd(FormCollection form)
        {
            var _msg = Msg.Create();

            var _oldPwd = form["oldpwd"].Password();

            string _pwd = string.Empty;

            if (!string.IsNullOrEmpty(form["pwd"]))
            {

                _pwd = form["pwd"].Password();

            }

            var _email = form["email"];

            ForumContext.UserInfo.Email = _email;

            if (UsersRepo.SaveEmailPwd(ForumContext.UserInfo.UserId, _oldPwd, _pwd, _email))
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "UPDATE_SUCCESS");
                if (!string.IsNullOrEmpty(_pwd))
                {

                    ForumContext.SignOut();

                    _msg.ReturnUrl = ForumContext.GetAbsoluteUrl(ForumUrls.LOGIN);
                }
            }
            else
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "OLD_PWD_INCORRECT");
            }


            return JavaScript(_msg.ToJavaScript());
        }

        #endregion


        #region Signature

        public ActionResult Signature()
        {

            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.SIGNATURE, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.SIGNATURE)
            };



            ViewBag.ActiveUrl = url;
            var _address = Address;
            _address.Add(url);
            ViewBag.NavAddress = _address;

            var _userInfo = UsersRepo.UserInfo(ForumContext.UserInfo.UserId);

            ViewBag.Signature = _userInfo.Signature;

            return View();



        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Signature(FormCollection form)
        {
            var _msg = Msg.Create();

            var _text = form["signature"].HtmlSanitize();

            if (_text.Length < 2000)
            {

                if (_text.HtmlToPlainText().Length == 0)
                    _text = string.Empty;

                UsersRepo.SaveSignature(ForumContext.UserInfo.UserId, _text);

                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "UPDATE_SUCCESS");
            }
            else
            {
                _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "LargeLength");
            }


            return JavaScript(_msg.ToJavaScript());
        }



        #endregion


        #region Avatar
        public ActionResult Avatar()
        {
            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.AVATAR, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.AVATAR)
            };

            ViewBag.ActiveUrl = url;
            var _address = Address;
            _address.Add(url);
            ViewBag.NavAddress = _address;

            return View();
        }


        [HttpPost]
        public ActionResult Avatar(int? chunk, string name)
        {
            var _uploadFile = Request.Files[0];
            //chunk = chunk ?? 0;
            if (_uploadFile != null)
            {




                string _fileName = string.Format("{0}{1}", DateTime.UtcNow.Ticks, Path.GetExtension(name));

                string filePath = string.Format("{0}{1}", ForumContext.Configuration.AvatarPath, _fileName);

                string _oldAvatar = Server.MapPath( string.Format("{0}{1}{2}",ForumContext.ApplicationPath, ForumContext.Configuration.AvatarPath,
                                                  ForumContext.UserInfo.Avatar));

                string uploadedFilePath = Server.MapPath(FileHelpers.PathCombine(ForumContext.ApplicationPath, filePath));


                int _w = ForumContext.Configuration.AvatarWidth;
                int _h = ForumContext.Configuration.AvatarHeight;

                ImageHelpers.ResizeStream(_uploadFile.InputStream, uploadedFilePath, _w, _h, null, 0, 0);

                /* using (var fs = new FileStream(uploadedFilePath, chunk == 0 ? FileMode.Create : FileMode.Append))
                 {
                     var buffer = new byte[fileUpload.InputStream.Length];
                     fileUpload.InputStream.Read(buffer, 0, buffer.Length);
                     fs.Write(buffer, 0, buffer.Length);
                 }*/


              
                ForumContext.UserInfo.Avatar = _fileName;

                UsersRepo.SaveAvatar(ForumContext.UserInfo.UserId, _fileName);

                if (System.IO.File.Exists(_oldAvatar))
                    System.IO.File.Delete(_oldAvatar);

                return Content("Upload completed", "text/plain");

            }


            return Content("Upload false", "text/plain");

        }
        #endregion


        #region Profile
        public ActionResult Profile()
        {
            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.PROFILE, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.PROFILE)
            };


            ViewBag.ActiveUrl = url;
            var _address = Address;
            _address.Add(url);
            ViewBag.NavAddress = _address;


            var _userInfo = UsersRepo.Info(ForumContext.UserInfo.UserId);


            var _sex = new List<SelectItem>
                           {
                              new SelectItem
                                   {
                                       Text = ForumContext.GetText(LanguageSection.USER_INFO, "Male"),
                                       Value = "true",
                                       Selected = _userInfo.Sex.HasValue && _userInfo.Sex.Value
                                   },
                               new SelectItem
                                   {
                                       Text = ForumContext.GetText(LanguageSection.USER_INFO, "Female"),
                                       Value = "false",
                                       Selected = _userInfo.Sex.HasValue && !_userInfo.Sex.Value
                                   }
                           };



            ViewBag.Sexs = _sex;


            return View(_userInfo);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Profile(FormCollection form)
        {
            var _msg = Msg.Create();


            /* var _sex = short.Parse(form["sex"]);

             var _birth = DateTime.Parse(form["birthday"]);*/


            var u = new User();
            TryUpdateModel(u, form.ToValueProvider());
            u.UserId = ForumContext.UserInfo.UserId;

            UsersRepo.SaveProfile(u);

            _msg.Text = ForumContext.GetText(LanguageSection.MESSAGES, "UPDATE_SUCCESS");

            return JavaScript(_msg.ToJavaScript());
        }
        #endregion


        #region Subscription


        public ActionResult TopicSubscribe()
        {

            ViewBag.SubscriptionType = SubscriptionType.Topic;

            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.SUBSCRIPTION, "TOPIC"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.TOPIC_SUBSCRIBE)
            };


            ViewBag.ActiveUrl = url;


            return Subcribe();

        }


        [HttpPost]
        public ActionResult TopicSubscribe(FormCollection form)
        {
            return Subcribe(form);
        }

        public ActionResult ForumSubscribe()
        {


            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.SUBSCRIPTION, "FORUM"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.FORUM_SUBSCRIBE)
            };


            ViewBag.ActiveUrl = url;

            ViewBag.SubscriptionType = SubscriptionType.Forum;

            return Subcribe();
        }

        [HttpPost]
        public ActionResult ForumSubscribe(FormCollection form)
        {
            return Subcribe(form);
        }

        public ActionResult Subcribe()
        {


            var _address = Address;
            var _url = ViewBag.ActiveUrl;

            if (_url == null)
            {
                _url = new ForumUrl
                           {
                               Title = ForumContext.GetText(LanguageSection.SUBSCRIPTION, "NEW_SUBCRIBE"),
                               Url = ForumContext.GetAbsoluteUrl(ForumUrls.SUBCRIBE)

                           };

                ViewBag.ActiveUrl = _url;

                //return View("_Subcribe");
            }


            _address.Add(_url);

            ViewBag.NavAddress = _address;



            #region Notify Type

            var _notifies = Enum.GetValues(typeof(NotificationType));

            var _notifyType = (from int val in _notifies
                               select new SelectListItem
                                          {
                                              Text = ForumContext.GetText(LanguageSection.SUBSCRIPTION, Enum.GetName(typeof(NotificationType), val)),
                                              Value = val.ToString()
                                          }).ToList();

            ViewBag.NotifyType = _notifyType;
            #endregion


            //var _act = Request.QueryString["do"];



            // Add Subcribe

            if (ViewBag.SubscriptionType == null)
            {

                if (!ForumContext.IsSuperMod && (!string.IsNullOrWhiteSpace(Request.QueryString["TopicId"]) && !ForumContext.UserInfo.Permissions.SubscribeToTopics || !string.IsNullOrWhiteSpace(Request.QueryString["ForumId"]) && !ForumContext.UserInfo.Permissions.SubscribeToForums))
                {
                    ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccessDenied);
                    return View("Message");
                }


                return View();
            }


            var _type = (SubscriptionType)ViewBag.SubscriptionType;

            int _pageIndex;

            int.TryParse(Request.QueryString["P"], out _pageIndex);
            if (_pageIndex <= 0)
                _pageIndex = 1;

            int _totalRows;

            const int _pageSize = 20;

            var _data = SubscriptionRepo.List(ForumContext.UserInfo.UserId, (short)_type, _pageIndex,
                                              _pageSize, out _totalRows);

            return View("Subscription", _data);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Subcribe(FormCollection form)
        {
            var _msg = Msg.Create();

            var _notify = short.Parse(form["notify"]);

            if (form["act"] == "add")
            {

                var _fid = form["ForumId"];
                var _tid = form["TopicId"];

                if (!string.IsNullOrWhiteSpace(_fid) || !string.IsNullOrWhiteSpace(_tid))
                {

                    int forumId, topicId;

                    int.TryParse(_fid, out forumId);
                    int.TryParse(_tid, out topicId);

                    SubscriptionRepo.Save(0, ForumContext.UserInfo.UserId, forumId, topicId, _notify);

                    _msg.ReturnUrl = form["returnUrl"];


                }
                else
                {
                    _msg.Text = ForumContext.GetText(LanguageSection.SUBSCRIPTION, "YOU_MUST_CHOOSE_ONE");
                }
            }
            else
            {
                var _ids = form["Id"].Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string id in _ids)
                {
                    SubscriptionRepo.Save(int.Parse(id), ForumContext.UserInfo.UserId, 0, 0, _notify);
                }
                _msg.Reload = true;

            }

            return JavaScript(_msg.ToJavaScript());
        }

        #endregion


        /*  #region Moderator

        public ActionResult Moderator()
        {
            return View();
        }

        #endregion*/


        public ActionResult SendEmail()
        {

            var url = new ForumUrl
            {
                Title = ForumContext.GetText(LanguageSection.SEND_EMAIL, "PAGE_NAME"),
                Url = ForumContext.GetAbsoluteUrl(ForumUrls.SEND_EMAIL)
            };


            var _add = Address;
            _add.Add(url);

            ViewBag.ActiveUrl = url;

            ViewBag.NavAddress = _add;


            if (ForumContext.IsSuperMod || (!string.IsNullOrWhiteSpace(Request.QueryString["TopicId"]) && ForumContext.UserInfo.Permissions.SendTopicsViaEmail) || ForumContext.UserInfo.Permissions.AllowSendEmail)
            {
                return View();
            }

            ViewBag.Message = ForumContext.GetText(LanguageSection.MESSAGES, Messages.AccessDenied);
            return View("Message");

        }

        public ActionResult Notification()
        {

            string cmd = Request["cmd"];

            if (cmd == "check")
            {

                var _total = NotificationRepo.Check(ForumContext.UserInfo.UserId, ForumContext.IsSuperMod,
                                                    ForumContext.UserInfo.LastNotifyCheck);

                return Json(new { Total = _total <= 99 ? _total.ToString() : "99+" }, JsonRequestBehavior.AllowGet);

            }


            int _pageIndex;
            int.TryParse(Request["p"], out _pageIndex);
            if (_pageIndex <= 0)
                _pageIndex = 1;

            var _pageSize = ForumContext.Configuration.PageSize;

            var _data = NotificationRepo.List(ForumContext.UserInfo.UserId, ForumContext.IsSuperMod, _pageIndex, _pageSize);

            ForumContext.UserInfo.LastNotifyCheck = DateTime.UtcNow;

            return View(_data);


        }

    }
}
